<?php
/**
 * 生成详细的API接口映射表
 * 基于oa_admin_rule表分析新旧系统接口对应关系
 */

// 引入自动加载文件
require_once 'vendor/autoload.php';

// 数据库配置
$config = [
    'hostname' => '116.62.146.217',
    'database' => 'oa',
    'username' => 'root',
    'password' => 'JyDmXg0407',
    'hostport' => '3306',
    'prefix'   => 'oa_',
    'charset'  => 'utf8mb4',
];

try {
    // 创建数据库连接
    $dsn = "mysql:host={$config['hostname']};port={$config['hostport']};dbname={$config['database']};charset={$config['charset']}";
    $pdo = new PDO($dsn, $config['username'], $config['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);

    // 查询oa_admin_rule表
    $stmt = $pdo->query("SELECT * FROM oa_admin_rule ORDER BY pid, id");
    $rules = $stmt->fetchAll();

    echo "========================================\n";
    echo "API接口映射分析\n";
    echo "========================================\n";

    // 建立ID到规则的映射
    $ruleMap = [];
    foreach ($rules as $rule) {
        $ruleMap[$rule['id']] = $rule;
    }
    
    // 按模块分组
    $modules = [];
    foreach ($rules as $rule) {
        $module = $rule['module'];
        if (!isset($modules[$module])) {
            $modules[$module] = [];
        }
        $modules[$module][] = $rule;
    }
    
    // 生成详细的API映射表
    $apiMapping = [];
    
    foreach ($modules as $moduleName => $moduleRules) {
        echo "\n【" . getModuleName($moduleName) . "】模块:\n";
        echo str_repeat("-", 50) . "\n";
        
        $moduleMapping = [
            'name' => getModuleName($moduleName),
            'endpoints' => []
        ];
        
        // 获取该模块的所有操作接口
        foreach ($moduleRules as $rule) {
            // 只处理有src路径的规则（即具体的操作接口）
            if (!empty($rule['src']) && $rule['menu'] == 2) {
                // 解析路由信息
                $endpoint = parseEndpoint($rule['src']);
                
                $endpointInfo = [
                    'title' => $rule['title'],
                    'name' => $rule['name'],
                    'src' => $rule['src'],
                    'module' => $rule['module'],
                    'controller' => $endpoint['controller'],
                    'action' => $endpoint['action'],
                    'http_method' => determineHttpMethod($rule['title']),
                    'new_endpoint' => '', // 待填写的新系统接口
                    'status' => 'pending' // pending, mapped, verified
                ];
                
                $moduleMapping['endpoints'][] = $endpointInfo;
                
                // 输出接口信息
                echo "  {$endpointInfo['http_method']} /{$endpointInfo['src']}\n";
                echo "    功能: {$endpointInfo['title']} ({$endpointInfo['name']})\n";
                echo "    控制器: {$endpointInfo['controller']}, 方法: {$endpointInfo['action']}\n";
                echo "    状态: 待映射\n\n";
            }
        }
        
        $apiMapping[$moduleName] = $moduleMapping;
    }
    
    // 保存API映射表到文件
    file_put_contents('api_mapping.json', json_encode($apiMapping, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    echo "API映射表已保存到 api_mapping.json 文件中\n";
    
    // 统计信息
    $totalEndpoints = 0;
    foreach ($apiMapping as $module) {
        $totalEndpoints += count($module['endpoints']);
    }
    
    echo "\n========================================\n";
    echo "统计信息\n";
    echo "========================================\n";
    echo "模块数量: " . count($apiMapping) . "\n";
    echo "接口总数: " . $totalEndpoints . "\n";

} catch (PDOException $e) {
    echo "数据库连接错误: " . $e->getMessage() . "\n";
} catch (Exception $e) {
    echo "错误: " . $e->getMessage() . "\n";
}

/**
 * 获取模块中文名称
 */
function getModuleName($module) {
    $moduleNames = [
        'home' => '系统管理',
        'base' => '基础数据',
        'user' => '人事管理',
        'adm' => '行政办公',
        'oa' => '办公OA',
        'finance' => '财务管理',
        'customer' => '客户管理',
        'contract' => '合同管理',
        'project' => '项目管理',
        'disk' => '知识网盘',
        'lawcase' => '案件管理',
        'lawyer' => '律所管理'
    ];
    
    return isset($moduleNames[$module]) ? $moduleNames[$module] : $module;
}

/**
 * 解析路由信息
 */
function parseEndpoint($src) {
    // 移除开头的斜杠
    $src = ltrim($src, '/');
    
    // 分割路径
    $parts = explode('/', $src);
    
    if (count($parts) >= 3) {
        // 标准格式: module/controller/action
        return [
            'module' => $parts[0],
            'controller' => $parts[1],
            'action' => $parts[2]
        ];
    } else if (count($parts) == 2) {
        // 格式: controller/action
        return [
            'module' => '',
            'controller' => $parts[0],
            'action' => $parts[1]
        ];
    } else {
        // 其他格式
        return [
            'module' => '',
            'controller' => '',
            'action' => $src
        ];
    }
}

/**
 * 根据操作名称确定HTTP方法
 */
function determineHttpMethod($title) {
    $title = strtolower($title);
    
    if (strpos($title, '新建') !== false || strpos($title, '新增') !== false || strpos($title, '添加') !== false) {
        return 'POST';
    } else if (strpos($title, '编辑') !== false || strpos($title, '修改') !== false || strpos($title, '更新') !== false) {
        return 'PUT';
    } else if (strpos($title, '删除') !== false || strpos($title, '移除') !== false) {
        return 'DELETE';
    } else {
        return 'GET';
    }
}